package org.swan;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

public class JTextFieldWithPlaceHolder extends JTextField {
    private final String placeHolder;
    private final Color defaultColor;
    public JTextFieldWithPlaceHolder(String placeholder) {
        super();
        this.placeHolder = placeholder;
        defaultColor = getForeground();
        addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                setStatus();
            }
            public void focusLost(FocusEvent e) {
                setStatus();
            }
        });
        setStatus();
    }
    public JTextFieldWithPlaceHolder(String placeholder,String text) {
        this(placeholder);
        setText(text);
    }


    @Override
    public void setText(String t) {
        super.setText(t);
        setStatus();
    }

    private void setStatus(){
        if(this.isFocusOwner())
            switchToText();
        else
            switchToPlaceHolder();
    }

    private void switchToPlaceHolder() {
        if(getText().isEmpty()) {
            super.setText(placeHolder);
            setForeground(Color.GRAY);
        }
    }
    private void switchToText(){
        if(getText().equals(placeHolder)) {
            super.setText("");
        }
        setForeground(defaultColor);
    }
}
